package com.glorystone.ins.service.impl;

import com.fastdfs.FastDFSClient;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.dao.*;
import com.glorystone.ins.domain.*;
import com.glorystone.ins.enums.FlowBusinessTypeEnum;
import com.glorystone.ins.enums.FlowOperateTypeEnum;
import com.glorystone.ins.enums.WorkFlowEnum;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.*;
import com.glorystone.ins.util.DictUtils;
import com.glorystone.ins.vo.ChannelHandleVO;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by wangwei on 2018/3/12.
 */
@Slf4j
@Service
public class ChannelServiceImpl implements ChannelService {

    /**
     * 1.查看详情 2.编辑 3.删除 4.渠道审核 5、垫资授信申请 6.授信初审 7.授信终审 8. 上传合同 9.风控复核 10.补齐保证金 11保证金确认
     */
    private static final int DETAIL = 1;
    private static final int EDIT = 2;
    private static final int DELETE = 3;
    private static final int CHANNEL_AUDIT = 4;
    private static final int CREDIT_APPLY = 5;
    private static final int CREDIT_FIRST = 6;
    private static final int CREDIT_LAST = 7;
    private static final int UPLOAD_CONTRACT = 8;
    private static final int CREDIT_REVIEW = 9;
    private static final int DEPOSIT_SUPPLEMENT = 10;
    private static final int DEPOSIT_ENSURE = 11;

    private static final int AUDIT_PASS = 1;
    private static final int AUDIT_REJECT = 2;


    @Autowired
    private ChannelMapper channelMapper;
    @Autowired
    private CreditTotalMapper creditTotalMapper;
    @Autowired
    private AttachmentMapper attachmentMapper;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${FASTADDR}")
    private String FASTADDR;

    @Autowired
    private AuditTaskService auditTaskService;
    @Autowired
    private BusinessLogService businessLogService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private CreditTotalService creditTotalService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private DepositRecordMapper depositRecordMapper;

    @Override
    public PageList<Channel> findList(PageVo vo) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int type = user.getType();
        if (type == 1) {
            // 外部用户， 渠道只能看到自己
            return channelMapper.findList(vo, vo.getPageable(), user.getTid());
        }
        return channelMapper.findList(vo, vo.getPageable(), null);

    }

    @Override
    public List<Channel> findAll() {
        return channelMapper.findAll();
    }

    @Override
    public List<Channel> findAllChannelName(String name) {
        return channelMapper.findAllChannelName(name);
    }

    @Override
    public Channel getById(Long tid) {

        Channel channel = channelMapper.getById(tid);

        List<Member> memberList = memberMapper.findByChannleId(tid);
        List<Member> actualControllerList = memberList.stream().filter(i -> i.getType() == Member.TypeEnum.ACTUAL_CONTROLLER.getValue()).collect(Collectors.toList());
        List<Member> seniorManagerList = memberList.stream().filter(i -> i.getType() == Member.TypeEnum.SENIOR_MANAGER.getValue()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(actualControllerList)) {
            channel.setActualController(actualControllerList.get(0));
        }
        channel.setSeniorManagerList(seniorManagerList);
        return channel;
    }

    @Override
    public Channel findByUserId(Long userId) {
        return channelMapper.findByUserId(userId);
    }

    @Override
    public List<Attachment> selectFileInfoByTid(Long tid) {
        List<Attachment> fileInfo = attachmentMapper.selectFileInfoByTid(tid);
        for (Attachment file : fileInfo) {
            String url = file.getUrl();
            url = FASTADDR + url;
            file.setUrl(url);
        }
        return fileInfo;
    }

    @Override
    public void handle(ChannelHandleVO handleVO, MultipartFile businessLicenseFile, MultipartFile industryLicenseFile, MultipartFile[] legalPersonFile, MultipartFile[] seniorManagerFile, MultipartFile[] actualControllerFile, MultipartFile[] contractsFile) {
        // 1.查看详情 2.编辑 3.删除 4.渠道审核 5、垫资授信申请 6.授信初审 7.授信终审 8. 上传合同 9.风控复核 10.补齐保证金 11保证金确认
        // 需要审批的操作： 4.渠道审核 5. 垫资授信申请 6.授信初审 7.授信终审 8.上传合同 9.风控复核 10.保证金确认
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();

        int type = handleVO.getOperateType();
        switch (type) {
            case CHANNEL_AUDIT:
                int result = handleVO.getAuditResult();
                if (result == AUDIT_PASS) {
                    // 审核通过
                    auditTaskService.submit(WorkFlowEnum.CREATE_CHANNEL, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);

                    // 修改渠道状态为已通过
                    Channel channel = new Channel();
                    channel.setTid(handleVO.getChannelId());
                    channel.setStatus(Channel.StatusEnum.CHANNEL_AUDIT_PASS.getValue());
                    channel.setUpdateBy(user.getTid());
                    channelMapper.update(channel);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CHANNEL_AUDIT_PASS, handleVO.getOpinion());

                } else if (result == AUDIT_REJECT) {
                    // 审核驳回
                    auditTaskService.submit(WorkFlowEnum.CREATE_CHANNEL, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    // 修改渠道状态为驳回
                    Channel channel = new Channel();
                    channel.setTid(handleVO.getChannelId());
                    channel.setStatus(Channel.StatusEnum.CHANNEL_AUDIT_REJECT.getValue());
                    channel.setUpdateBy(user.getTid());
                    channelMapper.update(channel);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CHANNEL_AUDIT_REJECT, handleVO.getOpinion());
                } else {
                    // nothing

                }


                break;
            case CREDIT_APPLY:
                // 授信额度申请 1. 工作流   2.查询是否存在还在生效的授信， 查询是否存在未还请的保证金，存在就不能申请 3.修改渠道状态为授信申请中  4. 操作日志


                auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.START);


                CreditTotal credit = creditTotalMapper.findCurrentByChannelId(handleVO.getChannelId());

                // 2018年3月19日16:48:06 目前存在的问题
                // 如果还存在生效中的授信， 那么提前申请下期的话，会造成渠道状态的改变，导致错误，目前产品确定方法是到期后才能申请，而不是提前申请

                // 不存在生效中的授信或者，已过期
                if (credit == null || credit.getStatus() == CreditTotal.StatusEnum.OFF.getValue()) {
                    credit = new CreditTotal();

                    credit.setChannelId(handleVO.getChannelId());
                    // 授信申请金额单位， 万元
                    credit.setApplyAmount(handleVO.getApplyAmount().multiply(BigDecimal.valueOf(10000)));
                    credit.setApplyPeriod(handleVO.getApplyPeriod());
                    credit.setStatus(CreditTotal.StatusEnum.WORK_FLOW.getValue());
                    credit.setCreateBy(user.getTid());

                    String rate  = DictUtils.getDictValue("1", "deposit_rate", null);
                    if (!Strings.isNullOrEmpty(rate)) {
                        credit.setDepositRate(new BigDecimal(rate));
                    }

                    creditTotalMapper.save(credit);
                } else {
                    // 存在生效中的授信，
                    log.warn("<-- 存在生效中的授信，不能再次申请！-->channelId-->{}, startDate-->{}, endDate-->{}", credit.getChannelId(), credit.getStartDate(), credit.getEndDate());

                }


                Channel channel = new Channel();
                channel.setTid(handleVO.getChannelId());
                channel.setStatus(Channel.StatusEnum.CREDIT_APPLY.getValue());
                channel.setUpdateBy(user.getTid());
                channelMapper.update(channel);


                // 保存公司实际控制人，和公司高管
                Member actual = handleVO.getActualController();
                if (actual != null) {
                    Member member = new Member();
                    member.setChannelId(handleVO.getChannelId());
                    member.setType(Member.TypeEnum.ACTUAL_CONTROLLER.getValue());
                    member.setName(actual.getName());
                    member.setIdNo(actual.getIdNo());
                    member.setMobile(actual.getMobile());
                    memberMapper.save(member);
                }

                List<Member> managers = handleVO.getSeniorManagerList();
                if (CollectionUtils.isNotEmpty(managers)) {
                    final Long channelId = handleVO.getChannelId();
                    managers = managers.stream().peek(i -> {
                        i.setType(Member.TypeEnum.SENIOR_MANAGER.getValue());
                        i.setChannelId(channelId);
                    }).collect(Collectors.toList());

                    memberMapper.saveList(managers);

                }


                // 保存附件
                attachmentService.save(businessLicenseFile, Attachment.AttachTypeEnum.BUSINESS_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
                attachmentService.save(industryLicenseFile, Attachment.AttachTypeEnum.INDUSTRY_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
                attachmentService.save(legalPersonFile, new Integer[]{Attachment.AttachTypeEnum.LEGAL_PERSON_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
                attachmentService.save(seniorManagerFile, new Integer[]{Attachment.AttachTypeEnum.SENIOR_MANAGER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
                attachmentService.save(actualControllerFile, new Integer[]{Attachment.AttachTypeEnum.ACTUAL_CONTROLLER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());


                // 记录操作日志
                businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_APPLY, null);

                break;
            case CREDIT_FIRST:
                // 1. 工作流 2. 操作日志
                int creditFirstResult = handleVO.getAuditResult();
                if (creditFirstResult == AUDIT_PASS) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);


                    Channel fistChannel = new Channel();
                    fistChannel.setTid(handleVO.getChannelId());
                    fistChannel.setStatus(Channel.StatusEnum.CREDIT_APPLY.getValue());
                    fistChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fistChannel);


                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_FIRST_PASS, handleVO.getOpinion());


                } else if (creditFirstResult == AUDIT_REJECT) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    Channel fistChannel = new Channel();
                    fistChannel.setTid(handleVO.getChannelId());
                    fistChannel.setStatus(Channel.StatusEnum.CREDIT_REJECT.getValue());
                    fistChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fistChannel);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_FIRST_REJECT, handleVO.getOpinion());

                }


                break;
            case CREDIT_LAST:
                // 1. 工作流  2. 授信信息  3. 操作日志
                int creditLastResult = handleVO.getAuditResult();
                if (creditLastResult == AUDIT_PASS) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);

                    Channel fistChannel = new Channel();
                    fistChannel.setTid(handleVO.getChannelId());
                    fistChannel.setStatus(Channel.StatusEnum.CREDIT_APPLY.getValue());
                    fistChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fistChannel);

                    CreditTotal creditTotal = creditTotalMapper.findOneInWorkFlow(handleVO.getChannelId());
                    creditTotal.setAcceptAmount(handleVO.getAcceptAmount().multiply(BigDecimal.valueOf(10000)));
                    creditTotal.setAcceptPeriod(handleVO.getAcceptPeriod());
                    creditTotal.setLastAmount(creditTotal.getAcceptAmount());
                    creditTotal.setAddUpAmount(BigDecimal.ZERO);
                    creditTotal.setAddUpReturnAmount(BigDecimal.ZERO);

                    CreditTotal prePhase = creditTotalMapper.findPrePhase(handleVO.getChannelId());
                    if (prePhase != null) {
                        creditTotal.setDepositPrePhaseAmount(prePhase.getDepositLastAmount());
                        // 上期保证金转到当期余额里
                        creditTotal.setDepositLastAmount(prePhase.getDepositLastAmount());
                    } else {
                        creditTotal.setDepositLastAmount(BigDecimal.ZERO);
                    }


                    creditTotal.setDepositAmount(handleVO.getAcceptAmount().multiply(BigDecimal.valueOf(10000)).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP).multiply(creditTotal.getDepositRate()));
                    creditTotal.setUpdateBy(user.getTid());
                    creditTotalMapper.update(creditTotal);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_LAST_PASS, handleVO.getOpinion());


                } else if (creditLastResult == AUDIT_REJECT) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    Channel fistChannel = new Channel();
                    fistChannel.setTid(handleVO.getChannelId());
                    fistChannel.setStatus(Channel.StatusEnum.CREDIT_REJECT.getValue());
                    fistChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fistChannel);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_LAST_REJECT, handleVO.getOpinion());

                }
                break;
            case UPLOAD_CONTRACT:

                // 1. 工作流  2. 授信信息 3.上传合同 4. 操作日志
                int fileResult = handleVO.getAuditResult();
                if (fileResult == AUDIT_PASS) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_APPLY.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);

                    CreditTotal creditTotal = creditTotalMapper.findOneInWorkFlow(handleVO.getChannelId());
                    creditTotal.setStartDate(handleVO.getStartDate());
                    creditTotal.setEndDate(handleVO.getEndDate());
                    creditTotalMapper.update(creditTotal);


                    // 保存合同
                    attachmentService.save(contractsFile, new Integer[]{Attachment.AttachTypeEnum.CREDIT_CONTRACT.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, handleVO.getChannelId());

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.UPLOAD_CONTRACT, handleVO.getOpinion());

                } else if (fileResult == AUDIT_REJECT) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_REJECT.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);


                    // 保存合同


                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.UPLOAD_CONTRACT, handleVO.getOpinion());
                } else {

                }


                break;
            case CREDIT_REVIEW:

                // 1. 工作流  2. 授信信息 3.上传合同 4. 操作日志
                int reviewResult = handleVO.getAuditResult();
                if (reviewResult == AUDIT_PASS) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_APPLY.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);

                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_REVIEW_PASS, handleVO.getOpinion());

                } else if (reviewResult == AUDIT_REJECT) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_REJECT.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);


                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.CREDIT_REVIEW_REJECT, handleVO.getOpinion());
                } else {

                }

                break;
            case DEPOSIT_ENSURE:

                // 1. 工作流  2. 授信信息通过 3.渠道通过 4. 操作日志
                int ensureResult = handleVO.getAuditResult();
                if (ensureResult == AUDIT_PASS) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.PASS);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_PASS.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);


                    CreditTotal total = creditTotalMapper.findOneInWorkFlow(handleVO.getChannelId());
                    total.setStatus(CreditTotal.StatusEnum.ON.getValue());

                    BigDecimal in = handleVO.getDepositInAmount();
                    BigDecimal out = handleVO.getDepositOutAmount();

                    BigDecimal firstLast = total.getDepositLastAmount().add(in);
                    BigDecimal secondLast = firstLast.subtract(out);

                    total.setDepositInAmount(in);
                    total.setDepositOutAmount(out);
                    total.setDepositLastAmount(total.getDepositLastAmount().add(in).subtract(out));
                    creditTotalMapper.update(total);


                    // 保证金操作记录
                    // 这里记录保证金操作记录
                    DepositRecord record = DepositRecord.builder()
                            .channelId(handleVO.getChannelId())
                            .lastAmount(firstLast)
                            .creditId(total.getTid())
                            .operateAmount(in)
                            .type(DepositRecord.TypeEnum.PAY.getValue())
                            .content(DepositRecord.TypeEnum.PAY.getContent())
                            .build();
                    DepositRecord record5 = DepositRecord.builder()
                            .channelId(handleVO.getChannelId())
                            .lastAmount(secondLast)
                            .creditId(total.getTid())
                            .operateAmount(out)
                            .type(DepositRecord.TypeEnum.RETURN_DEPOSIT.getValue())
                            .content(DepositRecord.TypeEnum.RETURN_DEPOSIT.getContent())
                            .build();
                    depositRecordMapper.save(record);
                    depositRecordMapper.save(record5);



                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.DEPOSIT_ENSURE, handleVO.getOpinion());

                } else if (ensureResult == AUDIT_REJECT) {
                    auditTaskService.submit(WorkFlowEnum.CREDIT_QUOTA, FlowBusinessTypeEnum.CHANNEL, handleVO.getChannelId(), FlowOperateTypeEnum.REJECT);

                    Channel fileChannel = new Channel();
                    fileChannel.setTid(handleVO.getChannelId());
                    fileChannel.setStatus(Channel.StatusEnum.CREDIT_REJECT.getValue());
                    fileChannel.setUpdateBy(user.getTid());
                    channelMapper.update(fileChannel);


                    // 记录操作日志
                    businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.DEPOSIT_ENSURE, handleVO.getOpinion());
                } else {

                }

                break;
            case DEPOSIT_SUPPLEMENT:
                // 补齐保证金
                creditTotalService.operateDeposit(handleVO.getChannelId(), DepositRecord.TypeEnum.SUPPLEMENT, handleVO.getSupplementDepositAmount(), handleVO.getOpinion());

                // 记录操作日志
                businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, handleVO.getChannelId(), BusinessLog.ContentEnum.DEPOSIT_COMPLETE, handleVO.getOpinion());
                break;
            default:
                break;
        }


    }

    @Override
    public void updateToCreditOverdue(List<Long> ids) {
        channelMapper.updateToCreditOverdue(ids);
    }

    @Override
    public void deleteById(Long tid) {
        channelMapper.deleteById(tid);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void update(Channel channel, MultipartFile businessLicenseFile, MultipartFile industryLicenseFile, MultipartFile[] legalPersonFile, MultipartFile[] seniorManagerFile, MultipartFile[] actualControllerFile, MultipartFile[] contactsFile,MultipartFile[] file, String[] alias) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        attachmentService.save(businessLicenseFile, Attachment.AttachTypeEnum.BUSINESS_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(industryLicenseFile, Attachment.AttachTypeEnum.INDUSTRY_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(legalPersonFile, new Integer[]{Attachment.AttachTypeEnum.LEGAL_PERSON_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(seniorManagerFile, new Integer[]{Attachment.AttachTypeEnum.SENIOR_MANAGER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(actualControllerFile, new Integer[]{Attachment.AttachTypeEnum.ACTUAL_CONTROLLER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(contactsFile, new Integer[]{Attachment.AttachTypeEnum.CONTACT_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(file, new Integer[]{Attachment.AttachTypeEnum.OTHER.getValue()}, alias, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());

        SysUser sysUser=new SysUser();
        sysUser.setTid(channel.getUserId().longValue());
        sysUser.setPhone(channel.getContact().getTelephone());
        sysUser.setRealName(channel.getContact().getName());
        sysUserService.updateUser(sysUser);

        channel.setStatus(Channel.StatusEnum.CREATE_CHANNEL.getValue());
        channel.setUpdateBy(user.getTid());
        channelMapper.update(channel);

        Member legalPerson = channel.getLegalPerson();
        legalPerson.setType(Member.TypeEnum.LEGAL_PERSON.getValue());
        legalPerson.setChannelId(channel.getTid());
        memberMapper.update(legalPerson);

        Member contact = channel.getContact();
        contact.setType(Member.TypeEnum.CONTACT.getValue());
        contact.setChannelId(channel.getTid());
        memberMapper.update(contact);

        memberMapper.deleteSeniorManagerByChannelId(channel.getTid());

        if (CollectionUtils.isNotEmpty(channel.getSeniorManagerList())) {
            List<Member> seniorManagerList = channel.getSeniorManagerList().stream().peek(i -> {
                i.setChannelId(channel.getTid());
                i.setType(Member.TypeEnum.SENIOR_MANAGER.getValue());
            }).collect(Collectors.toList());

            memberMapper.saveList(seniorManagerList);
        }

        auditTaskService.submit(WorkFlowEnum.EDIT_CHANNEL, FlowBusinessTypeEnum.CHANNEL,channel.getTid(), FlowOperateTypeEnum.START);
        businessLogService.save(BusinessLog.BusinessTypeEnum.CHANNEL, channel.getTid(),BusinessLog.ContentEnum.EDIT,null);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void updatePreChannel(Channel channel, MultipartFile businessLicenseFile, MultipartFile industryLicenseFile, MultipartFile[] legalPersonFile, MultipartFile[] seniorManagerFile, MultipartFile[] actualControllerFile, MultipartFile[] contactsFile, MultipartFile[] file, String[] alias) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        attachmentService.save(businessLicenseFile, Attachment.AttachTypeEnum.BUSINESS_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(industryLicenseFile, Attachment.AttachTypeEnum.INDUSTRY_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(legalPersonFile, new Integer[]{Attachment.AttachTypeEnum.LEGAL_PERSON_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(seniorManagerFile, new Integer[]{Attachment.AttachTypeEnum.SENIOR_MANAGER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(actualControllerFile, new Integer[]{Attachment.AttachTypeEnum.ACTUAL_CONTROLLER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(contactsFile, new Integer[]{Attachment.AttachTypeEnum.CONTACT_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(file, new Integer[]{Attachment.AttachTypeEnum.OTHER.getValue()}, alias, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());

        SysUser sysUser=new SysUser();
        sysUser.setTid(new Long(channel.getUserId()));
        sysUser.setPhone(channel.getContact().getTelephone());
        sysUser.setRealName(channel.getContact().getName());
        sysUserService.updateUser(sysUser);

        channel.setStatus(Channel.StatusEnum.CREATE_CHANNEL.getValue());
        channel.setUpdateBy(user.getTid());
        channelMapper.update(channel);

        Member contact = channel.getContact();
        contact.setType(Member.TypeEnum.CONTACT.getValue());
        contact.setChannelId(channel.getTid());
        memberMapper.update(contact);

    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void saveChannel(Channel channel, MultipartFile businessLicenseFile, MultipartFile industryLicenseFile, MultipartFile[] legalPersonFile, MultipartFile[] seniorManagerFile, MultipartFile[] actualControllerFile,MultipartFile[] contactsFile,MultipartFile[] file, String[] alias) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();


        SysUser sysUser=new SysUser();
        sysUser.setPhone(channel.getContact().getTelephone());
        sysUser.setUsername(channel.getJobNumber());
        sysUser.setJobNumber(channel.getJobNumber());
        sysUser.setRealName(channel.getContact().getName());
        sysUser.setChannelType(channel.getType());
        sysUserService.insertExternalUser(sysUser);


        channel.setUserId(sysUser.getTid().intValue());
        channel.setStatus(Channel.StatusEnum.CREATE_CHANNEL.getValue());
        channel.setCreateAt(LocalDateTime.now());
        channel.setCreateBy(user.getTid());
        channel.setDelFlag(0);
        channelMapper.insert(channel);

        if(businessLicenseFile!=null){
            attachmentService.save(businessLicenseFile, Attachment.AttachTypeEnum.BUSINESS_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        }else if(industryLicenseFile!=null){
            attachmentService.save(industryLicenseFile, Attachment.AttachTypeEnum.INDUSTRY_LICENSE.getValue(), null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        }
        attachmentService.save(legalPersonFile, new Integer[]{Attachment.AttachTypeEnum.LEGAL_PERSON_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(seniorManagerFile, new Integer[]{Attachment.AttachTypeEnum.SENIOR_MANAGER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(actualControllerFile, new Integer[]{Attachment.AttachTypeEnum.ACTUAL_CONTROLLER_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(contactsFile,new Integer[]{Attachment.AttachTypeEnum.CONTACT_ID_NO.getValue()}, null, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());
        attachmentService.save(file, new Integer[]{Attachment.AttachTypeEnum.OTHER.getValue()}, alias, Attachment.BusinessTypeEnum.CHANNEL, channel.getTid());


      if(channel.getType()==Channel.TypeEnum.TYPE_PERSON.getValue()){
           Member contact = channel.getContact();
           contact.setType(Member.TypeEnum.CONTACT.getValue());
           contact.setChannelId(channel.getTid());
           memberMapper.insertMember(contact);

       }else if(channel.getType()==Channel.TypeEnum.TYPE_COMPANY.getValue()){
           Member legalPerson = channel.getLegalPerson();
           legalPerson.setType(Member.TypeEnum.LEGAL_PERSON.getValue());
           legalPerson.setChannelId(channel.getTid());
           memberMapper.insertMember(legalPerson);

           Member contact = channel.getContact();
           contact.setType(Member.TypeEnum.CONTACT.getValue());
           contact.setChannelId(channel.getTid());
           memberMapper.insertMember(contact);

       }


    }

}
